package com.example.demo.controller;

import com.example.demo.common.AjaxResult;
import com.example.demo.common.ArticleInfoUtils;
import com.example.demo.common.UserSessionUtils;
import com.example.demo.entity.Articleinfo;
import com.example.demo.entity.Comment;
import com.example.demo.entity.UserInfo;
import com.example.demo.entity.vo.ArticleinfoVo;
import com.example.demo.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.xml.crypto.Data;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

import static java.time.LocalDateTime.*;

@RestController
@RequestMapping("/art")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    private Object lock = new Object();

    @RequestMapping("/mylist")
    public AjaxResult getMyList(HttpServletRequest request){
        UserInfo userInfo = UserSessionUtils.getUser(request);
        if(userInfo == null){
            return AjaxResult.fail(-1,"非法请求");
        }
        List<Articleinfo> list = articleService.getMyList(userInfo.getId());
        for(int i = 0; i< list.size();i++){
            if(list.get(i).getContent().length() > 150){
                list.get(i).setContent(list.get(i).getContent().substring(0,150));
            }
        }
        return AjaxResult.success(list);
    }

    @RequestMapping("/comments")
    public AjaxResult getComments(Integer blog_id){
        if(blog_id == null || blog_id <= 0){
            return AjaxResult.fail(-1,"参数异常");
        }
        List<Comment> list = articleService.comments(blog_id);
        return  AjaxResult.success(list);
    }

    @RequestMapping("/addcomment")
    public AjaxResult addComment(HttpServletRequest request,String contents,Integer blog_id){
        if (blog_id == null || blog_id <= 0 || contents == null){
            return AjaxResult.fail(-1,"参数异常");
        }
        UserInfo user = UserSessionUtils.getUser(request);
        if (user == null){
            return AjaxResult.fail(-2,"用户未登录");
        }
        return AjaxResult.success(articleService.addcomment(user.getUsername(),contents,blog_id));
    }


    @RequestMapping("/del")
    public AjaxResult del(HttpServletRequest request,Integer id){
        if (id == null || id <= 0 ){
            return AjaxResult.fail(-1,"参数异常");
        }
        UserInfo user = UserSessionUtils.getUser(request);
        if (user == null){
            return AjaxResult.fail(-2,"用户未登录");
        }
        return AjaxResult.success(articleService.del(id, user.getId()));
    }

    @RequestMapping("/detail")
    public AjaxResult getDetail(Integer id){
        if (id==null || id<=0){
            return AjaxResult.fail(-1,"非法参数");
        }
        return AjaxResult.success(articleService.getDetail(id));
    }

    @RequestMapping("/addupvote")
    public AjaxResult addUpvote(Integer blog_id){
        if(blog_id != null && blog_id > 0){
            articleService.addUpvote(blog_id);
            return AjaxResult.success(1);
        }

        return AjaxResult.fail(-1,"未知错误");
    }

    @RequestMapping("/incr-rcount")
    public AjaxResult incrRCount(Integer id){
        if(id != null && id > 0){
            return AjaxResult.success(articleService.incrRCount(id));
        }
        return AjaxResult.fail(-1,"未知错误");
    }

    @RequestMapping("/add")
    public AjaxResult add(HttpServletRequest request,Articleinfo articleinfo){
        // 1. 非空校验
        if(articleinfo == null || !StringUtils.hasLength(articleinfo.getTitle()) || !StringUtils.hasLength((articleinfo.getContent()))){
            // 非法参数
            return AjaxResult.fail(-1,"非法参数");
        }
        // 2. 数据库添加参数
        // 得到当前登录用户的 uid
        UserInfo userInfo = UserSessionUtils.getUser(request);
        if (userInfo == null || userInfo.getId() <= 0){
            // 无效的登录用户
            return AjaxResult.fail(-2,"无效用户");
        }
        articleinfo.setUid(userInfo.getId());
        // 添加数据库并返回结果
        return AjaxResult.success(articleService.add(articleinfo));
    }

    @RequestMapping("draft")
    public AjaxResult draft(HttpServletRequest request,Articleinfo articleinfo){
            // 1. 非空校验
            if(articleinfo == null || !StringUtils.hasLength(articleinfo.getTitle()) || !StringUtils.hasLength((articleinfo.getContent()))){
                // 非法参数
                return AjaxResult.fail(-1,"非法参数");
            }
            // 2. 数据库添加参数
            // 得到当前登录用户的 uid
            UserInfo userInfo = UserSessionUtils.getUser(request);
            if (userInfo == null || userInfo.getId() <= 0){
                // 无效的登录用户
                return AjaxResult.fail(-2,"无效用户");
            }
            articleinfo.setUid(userInfo.getId());

            // 添加数据库并返回结果
            return AjaxResult.success(articleService.draft(articleinfo));
    }

    @RequestMapping("/update")
    public AjaxResult update(HttpServletRequest request, Articleinfo articleinfo){
        // 非空校验
        if(articleinfo == null || !StringUtils.hasLength(articleinfo.getTitle() )|| !StringUtils.hasLength((articleinfo.getContent())) || articleinfo.getId() == null){
            // 非法参数
            return AjaxResult.fail(-1,"非法参数");
        }

        // 得到当前登录用户的 uid
        UserInfo userInfo = UserSessionUtils.getUser(request);
        if (userInfo == null || userInfo.getId() <= 0){
            // 无效的登录用户
            return AjaxResult.fail(-2,"无效用户");
        }

        // 修改文章的归属人
        articleinfo.setUid(userInfo.getId());

        // 发布草稿
        articleService.updateState(articleinfo.getId());

        // 修改时间
        articleinfo.setUpdatetime(LocalDateTime.now());

        // 添加数据库并返回结果
        return AjaxResult.success(articleService.update(articleinfo));
    }

    /**
     * 查询列表根据分页
     *
     * @param pindex 当前页码
     * @param psize  每页显示条数
     * @return
     */
    @RequestMapping("/listbypage")
    public AjaxResult getListByPage(Integer pindex,Integer psize){
        // 1. 参数校正
        if(pindex == null || pindex <= 1){
            pindex = 1;
        }
        if(psize == null || psize <= 1){
            psize = 2;
        }

        // 分页公式的值 = (当前页码-1)*每页显示条数
        int offset = (pindex - 1) * psize;
        // 文章列表数据
        List<Articleinfo> list = articleService.getListByPage(psize,offset);

        // 去除草稿
        for(int i = 0; i < list.size(); i++){
            Articleinfo art = list.get(i);
            if(art.getState() == -1){
                list.remove(i);
            }
        }

        for(int i = 0; i< list.size();i++){
            if(list.get(i).getContent().length() > 150){
                list.get(i).setContent(list.get(i).getContent().substring(0,150));
            }
        }
        // 当前文章共有多少页
        // 1.共有多少条数据
        int totalCount = articleService.getCount();
        // 2.总条数/psize
        double pcountdb = totalCount / (psize * 1.0);
        // 3.使用进一法得到总页数
        int pcount = (int) Math.ceil(pcountdb);
        HashMap<String,Object> result = new HashMap<>();
        result.put("list",list);
        result.put("pcount",pcount);
        return AjaxResult.success(result);
    }

    @RequestMapping("/timeadd")
    public AjaxResult timeAdd(HttpServletRequest request, ArticleinfoVo articleinfoVo){
        // 非空校验
        if (articleinfoVo == null || !StringUtils.hasLength(articleinfoVo.getTitle()) ||
        !StringUtils.hasLength(articleinfoVo.getContent())){
            return AjaxResult.fail(403,"参数错误");
        }
        UserInfo userInfo = UserSessionUtils.getUser(request);
        if (userInfo == null || userInfo.getId() <= 0){
            return AjaxResult.fail(403,"参数错误");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Thread queryTime = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock){
                    while (true){
                        if(ArticleInfoUtils.checkOvertime(sdf.format(System.currentTimeMillis()),articleinfoVo.getPostTime())){
                            Articleinfo articleinfo = new Articleinfo();
                            articleinfo.setTitle(articleinfoVo.getTitle());
                            articleinfo.setContent(articleinfoVo.getContent());
                            articleinfo.setUid(userInfo.getId());

                            articleService.add(articleinfo);
                            break;
                        }

                        try {
                            //休眠一分钟
                            System.out.println("休眠一分钟");
                            lock.wait(60000);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        });
        queryTime.start();
        return AjaxResult.success(1);
    }
}
